package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author stone
 * @date 2022/08/04 14:27
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountMapper accountMapper;

    /*@Autowired
    PlatformTransactionManager platformTransactionManager;*/

    @Autowired
    TransactionTemplate transactionTemplate;

    @Override
    public void transfer(int fromId, int destId, Integer money) {
        //transactionTemplate.execute();//execution方法中需要传入参数
        // 经过上面的分析，需要提供一个TransactionCallBack的实例，
        // 这个对象里有提供方法doInTransaction
        // transactionTemplate的execute方法是给doInTransaction方法增加事务
        // 把需要增加事务的代码放到doInTransaction中

        // 匿名内部类
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                // 先查询
                Integer fromMoney = accountMapper.selectMoneyById(fromId);
                Integer destMoney = accountMapper.selectMoneyById(destId);
                // 计算转账后的money
                fromMoney -= money;
                destMoney += money;
                // 更新money

                int from = accountMapper.update(fromId, fromMoney);
                int i = 1 / 0;
                int dest = accountMapper.update(destId, destMoney);
                return null;
            }
        });


    }
}
